import {
  CheckOutlined,
  CloseOutlined,
  DeleteOutlined,
  EditOutlined,
  MessageOutlined,
} from '@ant-design/icons';
import { Button, ButtonProps, Input, Popconfirm } from 'antd';
import React, { useState } from 'react';

interface Iprops {
  onDelete?: () => void; // 删除
  onChange?: (value: string) => void; // 修改
  isSeleted?: boolean; // 是否选中
  desc: string;
}

// 操作btn，封装啦颜色和种类
const OperatorButton = (
  props: ButtonProps & React.RefAttributes<HTMLElement>,
) => {
  return <Button type='text' style={{ color: '#004cce' }} {...props} />;
};

// 消息展示组件
const ChatItem: React.FC<Iprops> = ({
  onChange,
  onDelete,
  isSeleted,
  desc,
}: Iprops) => {
  const [showEdit, setShowEdit] = useState(false);
  const [inputValue, setInputValue] = useState(desc);

  // 取消修改
  const cancleEdit = () => {
    setShowEdit(false);
    setInputValue(desc); // 复原
  };

  // 确定修改
  const confirmEdit = () => {
    setShowEdit(false);
    onChange?.(inputValue); // 提交修改
  };

  return (
    <div
      className='h-[48px] bg-gray-200 flex items-center justify-between pl-4 pr-1 rounded-xl hover:cursor-pointer hover:bg-[#cedffa]'
      style={
        isSeleted
          ? {
              backgroundColor: '#cedffa',
              border: '1px solid #004cce',
              color: '#004cce',
            }
          : {}
      }>
      <div className='flex items-center justify-start'>
        <MessageOutlined />
        <div className='ml-3'>
          {showEdit ? (
            <Input
              value={inputValue}
              className='w-full text-base text-left'
              bordered={false}
              autoFocus={showEdit}
              onChange={(e) => setInputValue(e.target.value)}
            />
          ) : (
            inputValue
          )}
        </div>
      </div>
      <div className='flex'>
        {!showEdit && isSeleted && (
          <>
            <OperatorButton
              onClick={() => setShowEdit(true)}
              icon={<EditOutlined />}
            />
            <Popconfirm
              title='是否要删除这个聊天'
              onConfirm={() => onDelete?.()}
              okText='是'
              cancelText='否'>
              <div>
                <OperatorButton icon={<DeleteOutlined />} />
              </div>
            </Popconfirm>
          </>
        )}
        {showEdit && (
          <>
            <OperatorButton onClick={confirmEdit} icon={<CheckOutlined />} />
            <OperatorButton onClick={cancleEdit} icon={<CloseOutlined />} />
          </>
        )}
      </div>
    </div>
  );
};

export default ChatItem;
